<template>
  <div v-if="editOpen">
    <t-table :selected-row-keys="selectedRowKeys"
             @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data"
             :columns="columns">
      <template #sort="{ rowIndex }">
        [{{ rowIndex + 1 }}]
      </template>
      <template #name="{ row }">
        <t-input clearable @change="()=>{ if(row.name!==''){row.status='default'} }" :status="row.status"
                 v-model="row.name">
          <div slot="tips" v-if="row.status==='error'">不能为空</div>
        </t-input>
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table rowKey="id" :data="data"
             :columns="columns2">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #name="{ row,rowIndex }">
        <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].name!==row.name?'red':''}">
          {{ row.name }}
        </span>
      </template>
    </t-table>
  </div>
</template>

<script>
export default {
  name: "project-background-literature",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
    useOldData: {
      type: Boolean,
      default: false
    },
    oldData: {
      type: Array,
      default: () => [],
    },
    projectId: [String, Number],
    phaseType: {
      type: String,
      default: '1'
    },
  },
  data() {
    return {
      selectedRowKeys: [],
      dialogOpen: false,
      header: '新增参考文献',
      visible: true,
      formData: {
        sort: null,
        name: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: "不能为空",
          }
        ],
      },
      data: [],
      diffData: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'name',
          title: "参考文献",
          align: "left",
          ellipsis: true
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'name',
          title: "参考文献",
          align: "left",
          ellipsis: true
        },
      ]
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        if(val && val.length>0 && this.useOldData){
          let newArr = val.map(data=>{
            return {
              ...data,
              initType: 'init'
            }
          })
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },
    projectId: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          this.getData(val);
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
    oldData: {
      deep: true,
      immediate: true,
      handler(val) {
       this.diffData = this.oldData;
      }
    },
  },
  created() {

  },
  methods: {
    getData() {
      // 显示外层带的数据不查询
      if(this.useOldData){
        return false;
      }
      this.$api.kjxm.project.literatureGet(this.projectId, this.phaseType).then(res => {
        this.data = res.data;
        if (res.data.length <= 0 && this.phaseType !== '1' && this.editOpen === true) {
          this.$api.kjxm.project.literatureGet(this.projectId, Number(this.phaseType) - 1 > 0 ? Number(this.phaseType) - 1 : 1).then(res2 => {
            this.data = res2.data;
          }).catch((e) => {
            this.$message.error(e.toString());
          });
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if (val.name === "") {
          this.$set(this.data[index], 'status', 'error')
          this.$message.error(`主要参考文献：第${index + 1}条内容不能为空`);
          return false;
        }
        this.$set(this.data[index], 'status', 'default')
        return true;
      });
      return isValidate;
    },
    addData() {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        name: ''
      })
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.data.push({
            id: Number(new Date().getTime()) + Number(Math.random() * 10),
            ...this.formData
          })
          this.$refs.form.reset();
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
//.t-form__item {
//  margin-bottom: var(--td-comp-margin-xxl);
//  margin-right: 0px
//}
</style>
